<template>
  <el-dialog :title="form.id ? '编辑' : '新增'" v-model="visible"
             :close-on-click-modal="false" draggable>
    <el-form ref="dataFormRef" :model="form" :rules="dataRules" formDialogRef label-width="90px" v-loading="loading">
      <el-row :gutter="24">
        <el-col :span="24" class="mb20">
          <el-form-item label="客户名称" prop="name" >
            <el-input v-model="form.name" placeholder="请输入客户名称" :readonly="!!form.id" />
          </el-form-item>
        </el-col>

        <el-col :span="24" class="mb20">
          <el-form-item label="code" prop="code">
            <el-input v-model="form.code" placeholder="请输入code" :readonly="!!form.id" />
          </el-form-item>
        </el-col>

<!--        <el-col :span="24" class="mb20">-->
<!--          <el-form-item label="状态" prop="status">-->
<!--            <el-select v-model="form.status" placeholder="请选择状态">-->
<!--              <el-option :label="item.label" :value="parseInt(item.value)" v-for="(item, index) in cstm_customer_status"-->
<!--                         :key="index"></el-option>-->
<!--            </el-select>-->
<!--          </el-form-item>-->
<!--        </el-col>-->

        <el-col :span="24" class="mb20">
          <el-form-item label="公司账号" prop="corporateId">
            <el-select v-model="form.corporateId" placeholder="请选择公司账号" :disabled="!!form.id" >
              <el-option :label="item.name" :value="item.id" v-for="(item, index) in allCstmCorporates"
                         :key="index"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="24" class="mb20">
          <el-form-item label="单价" prop="price">
            <el-input v-model="form.price" placeholder="请输入单价"/>
          </el-form-item>
        </el-col>
        <el-col :span="24" class="mb20">
          <el-form-item label="接入方式" prop="method">
            <el-select v-model="form.method" placeholder="请选择接入方式"  :disabled="!!form.id" >
              <el-option label="CMPP" value="cmpp"></el-option>
              <el-option label="HTTP" value="http"></el-option>
            </el-select>
          </el-form-item>
        </el-col>


      </el-row>
    </el-form>
    <template #footer>
        <span class="dialog-footer">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" @click="onSubmit" :disabled="loading">确认</el-button>
        </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="customerCstmCustomerDialog">
import {useDict} from '/@/hooks/dict';
import {useMessage} from "/@/hooks/message";
import {getObj, addObj, putObj, newCstmCustomer} from '/@/api/bms/customer/customer'
import {rule} from '/@/utils/validate';
import {allCorporates} from "/@/api/bms/customer/corporate";
import {allCmppServerInfos} from "/@/api/bms/customer/cmppServerInfo";

const emit = defineEmits(['refresh']);

// 定义变量内容
const dataFormRef = ref();
const visible = ref(false)
const loading = ref(false)
// 定义字典
const {cstm_customer_status} = useDict('cstm_customer_status')

// 提交表单数据
const form = reactive({
  id: '',
  name: '',
  code: '',
  status: 0,
  method: '',
  corporateId: '',
  price: ''
});

// 定义校验规则
const dataRules = ref({
  name: [{required: true, message: '客户名称不能为空', trigger: 'blur'}],
  code: [{required: true, message: 'code不能为空', trigger: 'blur'}],
  status: [{required: true, message: '状态不能为空', trigger: 'blur'}],
  method: [{required: true, message: '接入方式不能为空', trigger: 'blur'}],
  corporateId: [{required: true, message: '公司账号不能为空', trigger: 'blur'}],
  price: [{required: true, message: '单价不能为空', trigger: 'blur'}],
})

// 打开弹窗
const openDialog = (id: string) => {
  visible.value = true
  form.id = ''

  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields();
    // 如果已有选择的协议，初始化对应的校验规则
    if (!form.id ) {
    }
  });

  // 获取cstmCustomer信息
  if (id) {
    form.id = id
    getCstmCustomerData(id)
  } else {
    newCstmCustomer().then((res: any) => {
      Object.assign(form, res.data)
    })
  }
};

// 提交
const onSubmit = async () => {
  const valid = await dataFormRef.value.validate().catch(() => {
  });
  if (!valid) return false;

  //深拷贝form到一个新的对象中
  // const formCopy = JSON.parse(JSON.stringify(form));
  // //methodParams只保留选中协议的数据，并且转化成json字符串
  // if (formCopy.method === 'cmpp') {
  //   formCopy.methodParams = JSON.stringify(formCopy.methodParams.cmpp);
  // } else if (formCopy.method === 'http') {
  //   formCopy.methodParams = JSON.stringify(formCopy.methodParams.http);
  // }
  console.log("onSumbit------", form)
  try {

    loading.value = true;
    form.id ? await putObj(form) : await addObj(form);
    useMessage().success(form.id ? '修改成功' : '添加成功');
    visible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg);
  } finally {
    loading.value = false;
  }
};


// 初始化表单数据
const getCstmCustomerData = (id: string) => {
  // 获取数据
  loading.value = true
  getObj(id).then((res: any) => {
    const { methodParams, ...restData } = res.data
    Object.assign(form, restData)
    // 单独处理methodParams
    if (form.method === 'cmpp' && methodParams) {
      let mp = JSON.parse(methodParams)
      // console.log("methodParams", mp, form.methodParams.cmpp)
      Object.assign(form.methodParams.cmpp, mp)
    }


  }).finally(() => {
    loading.value = false
  })
};


//加载所有的下游公司
const allCstmCorporates = ref([])
const getCstmCorporates = () => {
  allCorporates().then((res: any) => {
    console.log("allCstmCorporate", res)
    allCstmCorporates.value = res.data
  })
}
getCstmCorporates();

// 暴露变量
defineExpose({
  openDialog
});
</script>
